package com.king.springcloud.lb;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 自定义负载均衡实现
 * @author king
 * @date 2020/9/2 22:58
 */
@Slf4j(topic = "c.MyLoadBalanced")
@Component
public class MyLoadBalanced implements LoadBalanced {

    /**
     * 计数器
     */
    private AtomicInteger atomicInteger = new AtomicInteger(0);

    /**
     * 自旋更新计数器
     * @return 计数器自增 1
     */
    public final int getAndIncrement(){

        int current;
        int next;

        do{
            // 当前数值
            current = this.atomicInteger.get();
            // 下一个数值
            next = current >= Integer.MAX_VALUE - 1 ? 0 : current + 1;

            // 判断修改是否成功，不成功则进行自旋
        }while(!this.atomicInteger.compareAndSet(current, next));

        System.out.printf("第%d次访问%n", next);
        return next;
    }

    /**
     * 获取服务
     * @param serviceInstances 服务列表
     * @return 选中的服务
     */
    @Override
    public ServiceInstance instance(List<ServiceInstance> serviceInstances) {
        // 对服务列表取余实现轮询
        int index = getAndIncrement() % serviceInstances.size();

        // 返回选择服务节点
        return serviceInstances.get(index);
    }
}
